import { HttpClient } from '../utils/HttpClient';
import { UserProfile, ApiResponse } from '../types';

export class UserProfileService {
  private httpClient: HttpClient;

  constructor() {
    this.httpClient = new HttpClient();
  }

  /**
   * 获取用户资料
   */
  public async getUserProfile(): Promise<UserProfile | null> {
    try {
      const response = await this.httpClient.get<UserProfile>('/user/profile');
      
      if (response.success && response.data) {
        return response.data;
      } else {
        return null;
      }
    } catch (error) {
      console.error('Failed to get user profile:', error);
      return null;
    }
  }

  /**
   * 更新用户资料
   */
  public async updateUserProfile(data: Partial<UserProfile>): Promise<boolean> {
    try {
      const response = await this.httpClient.put('/user/profile', data);
      return response.success;
    } catch (error) {
      console.error('Failed to update user profile:', error);
      return false;
    }
  }

  /**
   * 更新用户头像
   */
  public async updateUserAvatar(avatarUrl: string): Promise<boolean> {
    try {
      const response = await this.httpClient.put('/user/avatar', { avatarUrl });
      return response.success;
    } catch (error) {
      console.error('Failed to update user avatar:', error);
      return false;
    }
  }

  /**
   * 获取LLM配置
   */
  public async getLLMConfig(): Promise<any> {
    try {
      const response = await this.httpClient.get('/user/llm-config');
      
      if (response.success && response.data) {
        return response.data;
      } else {
        return null;
      }
    } catch (error) {
      console.error('Failed to get LLM config:', error);
      return null;
    }
  }

  /**
   * 保存LLM配置
   */
  public async saveLLMConfig(config: any): Promise<boolean> {
    try {
      const response = await this.httpClient.put('/user/llm-config', config);
      return response.success;
    } catch (error) {
      console.error('Failed to save LLM config:', error);
      return false;
    }
  }

  /**
   * 测试LLM连接
   */
  public async testLLMConnection(config: any): Promise<{ success: boolean; message?: string }> {
    try {
      const response = await this.httpClient.post('/llm/test-connection', config);
      
      return {
        success: response.success,
        message: response.message
      };
    } catch (error) {
      console.error('Failed to test LLM connection:', error);
      return {
        success: false,
        message: '连接测试失败'
      };
    }
  }

  /**
   * 修改密码
   */
  public async changePassword(oldPassword: string, newPassword: string): Promise<boolean> {
    try {
      const response = await this.httpClient.put('/user/password', {
        oldPassword,
        newPassword
      });
      
      return response.success;
    } catch (error) {
      console.error('Failed to change password:', error);
      return false;
    }
  }

  /**
   * 导出用户数据
   */
  public async exportUserData(): Promise<string | null> {
    try {
      const response = await this.httpClient.get('/user/export');
      
      if (response.success && response.data) {
        return response.data.exportUrl;
      } else {
        return null;
      }
    } catch (error) {
      console.error('Failed to export user data:', error);
      return null;
    }
  }

  /**
   * 删除用户账户
   */
  public async deleteAccount(password: string): Promise<boolean> {
    try {
      const response = await this.httpClient.delete('/user/account', {
        'Content-Type': 'application/json'
      });
      
      return response.success;
    } catch (error) {
      console.error('Failed to delete account:', error);
      return false;
    }
  }

  /**
   * 验证用户输入的个人信息
   */
  public validateProfile(profile: Partial<UserProfile>): { isValid: boolean; errors: string[] } {
    const errors: string[] = [];

    // 验证出生日期
    if (profile.birthDate) {
      const birthDate = new Date(profile.birthDate);
      const today = new Date();
      const age = today.getFullYear() - birthDate.getFullYear();
      
      if (birthDate > today) {
        errors.push('出生日期不能是未来日期');
      } else if (age < 0 || age > 120) {
        errors.push('请输入有效的出生日期');
      }
    }

    // 验证身高
    if (profile.height !== undefined) {
      if (profile.height < 100 || profile.height > 250) {
        errors.push('身高应在100-250cm之间');
      }
    }

    // 验证体重
    if (profile.weight !== undefined) {
      if (profile.weight < 30 || profile.weight > 200) {
        errors.push('体重应在30-200kg之间');
      }
    }

    // 验证性别
    if (profile.gender && !['male', 'female', 'other'].includes(profile.gender)) {
      errors.push('请选择有效的性别');
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 计算年龄
   */
  public calculateAge(birthDate: string): number {
    const birth = new Date(birthDate);
    const today = new Date();
    let age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
      age--;
    }
    
    return age;
  }

  /**
   * 计算BMI
   */
  public calculateBMI(height: number, weight: number): number {
    if (height <= 0 || weight <= 0) return 0;
    const heightInMeters = height / 100;
    return Number((weight / (heightInMeters * heightInMeters)).toFixed(1));
  }

  /**
   * 获取BMI状态
   */
  public getBMICategory(bmi: number): string {
    if (bmi < 18.5) return '偏瘦';
    if (bmi < 24) return '正常';
    if (bmi < 28) return '超重';
    return '肥胖';
  }

  /**
   * 获取健康建议
   */
  public getHealthAdvice(profile: UserProfile): string[] {
    const advice: string[] = [];
    
    if (profile.height && profile.weight) {
      const bmi = this.calculateBMI(profile.height, profile.weight);
      
      if (bmi < 18.5) {
        advice.push('建议增加营养摄入，适当增重');
        advice.push('可以咨询营养师制定增重计划');
      } else if (bmi >= 24) {
        advice.push('建议控制饮食，增加运动量');
        advice.push('可以制定健康的减重计划');
      } else {
        advice.push('您的体重指数正常，请继续保持');
      }
    }
    
    if (profile.birthDate) {
      const age = this.calculateAge(profile.birthDate);
      
      if (age >= 40) {
        advice.push('建议定期进行健康体检');
        advice.push('注意心血管健康');
      }
      
      if (age >= 60) {
        advice.push('建议增加钙质摄入，预防骨质疏松');
        advice.push('适量进行低强度运动');
      }
    }
    
    return advice;
  }
}